<template>
  <div class="custom-card-box  work-root">

    <customCard :width="280"  :height="200"  class="custom-card-user" withAnimate>
      <template #title>
        您好，{{user.name}}
      </template>

      <template #avatar>
        <customImage :src="user.avatarUrl" :width="40" :height="40" style="display: inline-block" errorShowHpJpg/>
      </template>

      <template #content>
        <div class="custom-card-user-content">
          <p><span>所属部门: </span>{{user.deptName}}</p>
          <p><span>当前日期: </span>{{dates.getCurrentDate('yyyy年MM月dd日')}}</p>
          <p><span>客户端IP: </span>{{ cpVersionInfo.customIp}}</p>
          <p><span>PC版本: </span>{{ cpVersionInfo.versionWeb}}</p>
          <p><span>API版本: </span>{{cpVersionInfo.versionApi}}</p>
        </div>
      </template>
    </customCard>

    <customCard  withAnimate :width="516" :height="200" class="custom-card-settings">
      <template #title>
        <Icon class="card-icon" name="setting" style="color: #0f47d0" />
        <span style="vertical-align: middle">常用设置</span>
      </template>
      <template #content>
        <customForm :data="form" ref="form"  :labelWidth="80" >
          <template #content>
            <customFormItem
              label="当前仓库:"
              name="warehouseName"
              :parent="_self"
              :form="form"
              disabled
              :type="constCommon.formItemType.slot.name"
            >
              <template #content>
                {{cpWarehouseName}}
              </template>
            </customFormItem>

            <customFormItem
              label="上级仓库:"
              name="applyWarehouseName"
              :parent="_self"
              :type="constCommon.formItemType.slot.name"
              :form="form"
            >
              <template #content>
               <span>{{cpParentTitle}}</span>
              </template>
            </customFormItem>
            <customFormItem
              label="表单打印机:"
              name="printer_form_name"
              :parent="_self"
              :form="form"
              :readonly="true"
              :showSelectIcon="true"
              @focus="choicePrintServer('form')"
            />
            <customFormItem
              label="标签打印机:"
              name="printerServerName"
              :parent="_self"
              :form="form"
              :readonly="true"
              :showSelectIcon="true"
              @focus="choicePrintServer('label')"
            />
          </template>
        </customForm>
      </template>
    </customCard  >

    <customCard  withAnimate :height="200" style="width: calc(100% - 816px ); margin-right: 0">
      <template #title>
        <Icon class="card-icon" name="view-module" style="color: #0099ff" />
        <span style="vertical-align: middle">院内公告信息</span>
      </template>
      <template #actions>
        <customSpace>
          <template #content>
            <customButton @click="utils.openMenu('innernotice')"  title="历史公告" theme="primary" size="small" help="查看历史公告"/>
          </template>
        </customSpace>
      </template>
      <template #content>
        <div :class="'systemnotice-box ' + (workbenchListNews.length > 2 && 'systemnotice-box-height')">
          <div v-for="(ob, index) in workbenchListNews" :key="ob.id" class="systemnotice-item" :index="index">
            <div class="title">{{ ob.title }}</div>
            <div class="time">
              <i class="el-icon-time"></i>{{ new Date(ob.gmtSend).format('yyyy-MM-dd HH:mm:ss') }}
            </div>
            <div class="content" v-html="ob.content">{{ ob.content }}</div>
          </div>
          <p v-if="workbenchListNews.length < 1" class="empty">暂无信息</p>
        </div>
      </template>
    </customCard>

    <customCard  withAnimate :width="280" :height="500" class="custom-card-quick-menu">
      <template #title>
        <Icon class="card-icon" name="heart-filled" style="color: #fe494b" />
        <span style="vertical-align: middle">快捷操作({{workbenchListMenu.length}})</span>
      </template>
      <template #actions>
        <customSpace>
          <template #content>
            <customButton @click="getMenuQuickList(true)"  title="刷新" theme="success" size="small" help="刷新数据"/>
            <customButton @click="$refs.setMenuQuick.show()"  title="设置" theme="primary" size="small" help="设置快捷操作"/>
          </template>
        </customSpace>
      </template>
      <template #content>
        <div :class="'menu-list ' + (workbenchListMenu.length > 10 && 'menu-list-height')" style="margin-top: -6px">
          <div
            class="content"
            v-for="(ob, index) in workbenchListMenu"
            :key="ob.id"
            @click="utils.openMenu(ob.typeKey)"
          >
            <i
              :class="strings.defaultIfBlank(ob.icon, 'el-icon-star-off') + ' el-icon--left'"
              :style="'color: ' + ob.iconColor"
            ></i>
            <p style="font-size: 11px; line-height: 11px;height: 11px" class="div-NoWrap">{{ ob.title }}</p>
          </div>
          <p class="empty" v-if="workbenchListMenu.length < 1">尚未配置</p>
        </div>
      </template>
    </customCard>

    <customCard class="num-count-card"  withAnimate style="width: 516px; text-align: center"   :height="500">
      <template #title>
        <Icon class="card-icon" name="image" style="color: #409eff" />
        <span style="vertical-align: middle">业务统计</span>
      </template>
      <template #actions>
        <customSpace>
          <template #content>
            <customButton @click="getCountInfoList(true)"  title="刷新" theme="success" size="small" help="刷新统计数据"/>
          </template>
        </customSpace>
      </template>
      <template #content >
        <div class="custom-statistic-container">
          <customStatistic
            v-for="(item,index) in Object.values(cardData.countInfo)"
            :key="index"
            :title="item.title"
            :value="item.value"
            :unit="item.unit"
            :color="item.color"
            :extra="item.extra"
            trend="increase"
            :width="strings.defaultIfBlank(item.width, '210px')"
            height="120px"
            :class="'num-count-show-' + item.show"
            :marginRight="item.marginRight"
          />
        </div>
      </template>
    </customCard>

    <customCard   style="width: calc(100% - 816px); margin-right: 0" :height="500">
      <template #title>
        <Icon class="card-icon" name="add-rectangle" style="color: #e6a23c;" />
        <span style="vertical-align: middle">待办任务({{cardData.taskTodoSize}})</span>
      </template>
      <template #content>
        <taskTodo ref="taskTodo" @setSize="(taskTodoSize) => cardData.taskTodoSize  = taskTodoSize"/>
      </template>
    </customCard>

    <customCard style="width: 804px;"  :height="500" v-if="utils.isAdmin()">
      <template #title>
        <Icon class="card-icon" name="notification-filled" style="color: #fe9124" />
        <span style="vertical-align: middle">站内消息</span>
      </template>
      <template #content>
        <data-view
          ref="unreadDV"
          propViewKey="v_msg_inner_inbox"
          propViewForm="frame/msg/inner-inbox/detail.vue"
          :propPreQueryWrapper="cpMsgWrapper"
          @extra-button-click="handleExtraButtonClick"
          :propHeight="600"
          :propPageSize="6"
        />
      </template>
    </customCard>

    <customCard  style="width: calc(100% - 816px); margin-right: 0"   :height="500"  v-if="utils.isAdmin()">
      <template #title>
        <Icon class="card-icon" name="user-circle" style="color: #5cb85c;" />
        <span style="vertical-align: middle">在线用户</span>
      </template>
      <template #content>
        <data-view
          propViewKey="sys_online_user"
          :propHideColumns="['token']"
          :propHeight="600"
          :propPageSize="6"
          :propOnlyQueryAll="true"
        />
      </template>
    </customCard>

    <customCard   :height="500" style="width: calc(100%); margin-right: 0"  v-if="utils.isAdmin()">
      <template #title>
        <Icon class="card-icon" name="minus-rectangle" style="color: #f56c6c;" />
        <span style="vertical-align: middle">操作日志</span>
      </template>
      <template #content>
        <data-view
          propViewKey="sys_log"
          propViewForm="sys/log/detail.vue"
          :propHideColumns="['busTable', 'busKey', 'busId']"
          :propHeight="600"
          :propPageSize="6"
          :propOnlyQueryAll="true"
        />
      </template>
    </customCard>

    <customCard  style="width: calc(100%); margin-right: 0"   :height="560">
      <template #title>
        <Icon class="card-icon" name="user-circle" style="color: #5cb85c" />
        <span style="vertical-align: middle">库存效期提醒<small style="color:#dd4c4c; font-size: 12px; margin-left: 4px">(6个月以内及过期商品)</small></span>
      </template>
      <template #content>
        <Report  propReportKey="stock_exp_notice" style="width: 100%" :propPageSize="6" ></Report>
      </template>
    </customCard>

    <setMenuQuick ref="setMenuQuick" @change="getMenuQuickList"/>
  </div>
</template>

<script>
/* eslint-disable */
import { Icon } from 'tdesign-icons-vue'
import customCard from '@/components/custom/layout/customCard'
import customList from '@/components/custom/layout/customList'
import customListItem from '@/components/custom/layout/customListItem'
import customStatistic from '@/components/custom/form/customStatistic'
import customImage from '@/components/custom/form/customImage'
import Report from "@/components/report/Report.vue";
import taskTodo from "./taskTodo.vue";
import setMenuQuick from "./setMenuQuick.vue";
import utils from "@/util/utils";
import customUpload from '@/components/custom/form/customUpload.vue'
import warehouseSelect from '@/components/custom/bus/select/warehouseSelect.vue'

export default {
  name: 'dashboard',
  data() {
    return {
      form: {
        printerServerName: ''
      },
      user: {
        name: '',
        deptName: '',
      },
      workbenchListMenu: [],
      workbenchListOther: [],
      workbenchListNews: [],

      applyWarehouseName: '未设置',
      printAuto: false,
      winH: window.innerHeight,

      //数据
      cardData: {
        //待办数量
        taskTodoSize: 0,

        //统计数字列表
        countInfo: {
          // 科室申请
          deptApplyCount: {
            show: 0,
            title: '本月申领数',
            unit: '个',
            color: '#00CC00'
          },

          // 科室退货
          deptReturnCount: {
            show: 0,
            title: '本月科室退货',
            unit: '个',
            color: '#993333',
          },

          // 科室消耗
          deptCostAmount: {
            show: 0,
            title: '本月消耗金额',
            unit: '元',
            color: '#9933FF',
            width: '430px',
          },

          // 采购订单
          orderCount: {
            show: 0,
            title: '本月订单数',
            unit: '个',
            color: '#FF9900'
          },

          // 入库
          workInCount: {
            show: 0,
            title: '本月入库数',
            unit: '个',
            color: '#009966'
          },

          // 调拨出库
          workOutShiftCount: {
            show: 0,
            title: '本月调拨出库',
            unit: '个',
            color: '#CC6600'
          },

          // 供应商退货
          spOutCount: {
            show: 0,
            title: '本月供应商退货',
            unit: '个',
            color: '#993399'
          }
        }
      },
    }
  },
  watch: {
    // 用户状态改变，更新打印设置
    '$store.state.users.userState': {
      immediate: true, // 初始创建 watch 时立即执行回调函数
      deep: true, // 监听到对象里面的值的变化
      handler() {
        this.setPrint()
      },
    },
  },
  components: {
    warehouseSelect,
    customUpload,
    Report,
    Icon,
    customCard,
    customList,
    customListItem,
    customStatistic,
    taskTodo,
    setMenuQuick,
    customImage
  },
  computed: {
    utils() {
      return utils
    },
    cpParentTitle() {
      let userState = this.$store.state.users.userState
      if (userState && userState.workbenchWarehouse &&  userState.workbenchWarehouse.applyWarehouseName) {
        return  userState.workbenchWarehouse.applyWarehouseName
      }
      return '未设置'
    },
    cpMsgWrapper() {
      let _wrapper = this.$newWrapper()
      _wrapper.eq('contentType', 'news')
      _wrapper.orderBy('gmtSend')
      return _wrapper
    },
    // 版本信息
    cpVersionInfo() {
      let versionInfo = {
        versionWeb: '无',
        versionApi: '无',
        customIp: '无',
      }
      versionInfo.versionWeb = global.settings.versionWeb
      if (this.$store.state && this.$store.state.dicts && this.$store.state.dicts.systemProperties && this.$store.state.dicts.systemProperties.versionApi) {
        versionInfo.versionApi = this.$store.state.dicts.systemProperties.versionApi
      }
      if (this.$store.state && this.$store.state.dicts && this.$store.state.dicts.systemProperties && this.$store.state.dicts.systemProperties.customIp) {
        versionInfo.customIp = this.$store.state.dicts.systemProperties.customIp
      }
      return versionInfo
    },
    // 用户所选仓库
    cpWarehouseName() {
      let userState = this.$store.state.users.userState
      if (userState && userState.workbenchWarehouse &&  userState.workbenchWarehouse.warehouseName) {
        return  userState.workbenchWarehouse.warehouseName
      }
      return '未设置'
    }
  },
  methods: {
    //初始化工作区
    initWorkbench() {
      //获取用户仓库
      this.setPrint()

      //获取当前用户公告信息
      this.$ajax.get('sys/workbench/listNews').then((response) => {
        if (response.code == 0 && response.data && response.data.length > 0) {
          response.data.forEach((item) => this.workbenchListNews.push(item))
        }
      })
    },

    //选择打印服务器
    choicePrintServer(type) {
      if (type == 'label') {
        let param = {
          type: 'set',
        }
        global.utilPrint.openLabel(param)
        return
      }

      let param = {
        that: this, //当前调用对象
        isSet: true, //设置
      }
      global.utilPrint.openFormPrint(param)
    },

    //设置打印机
    setPrint() {
      //表单打印机名称
      const _printerFormName = this.utils.loadUserState(this, 'printerFormName')
      this.printer_form_name = _printerFormName
      this.$set(this.form, 'printer_form_name', _printerFormName)
      //表单打印机是否自动打印
      this.printAuto = this.utils.loadUserState(this, 'printerFormPrintAuto', null, true)

      //标签打印机名称
      let printerLabelConfig = this.utils.loadPrinterLabelConfig(this)
      if (printerLabelConfig) {
        this.$set(this.form, 'printerServerName', printerLabelConfig.printerServerName)
      }
    },


    loadArea(flagType, typeKey) {
      this.$refs[typeKey][0].fetchData()
    },
    handleExtraButtonClick(extra) {
      let {
        button: { key },
      } = extra
      if (key === 'vrb-read-all') {
        if (!this.$refs.unreadDV.tablePage.totalResult) {
          this.utilMessage.warning('当前已无待处理的消息')
          return
        }
        this.utilMessage.confirm('是否全部标记为已读？', () => {
          this.$ajax.put('/msg/inner_inbox/read_all').then((resp) => {
            this.utilMessage.success(resp.msg)
            this.$refs.unreadDV.fetchData()
          })
        })
      }
    },

    // 获取统计数据
    getCountInfoList(hasLoad) {
      if (hasLoad) {
        this.utilVue.loadShow(true)
      }
      let getUrl = `sys/workbench/loadInfo?getKey=getCountInfoList`
      Object.keys(this.cardData.countInfo).forEach(key2 => {
        this.$set(this.cardData.countInfo[key2], 'value', 0)
      })

      this.$ajax.get(getUrl).then((response) => {
        if (hasLoad) {
          this.utilVue.loadHide()
          this.utilMessage.success('数据刷新完成')
        }
        if (response.code == 0) {
          let index = 0
          Object.keys(response.data).forEach(key => {
            let countInfo = response.data[key]
            Object.keys(countInfo).forEach(key2 => {
              this.$set(this.cardData.countInfo[key], key2, countInfo[key2])
            })
          })
        }
      })
    },

    // 获取快捷菜单
    getMenuQuickList(hasLoad = false) {
      if (hasLoad) {
        this.utilVue.loadShow(true)
      }
      this.workbenchListMenu = []
      this.$ajax.get('sys/workbench/getByUserCode').then((response) => {
        if (response.code == 0) {
          if (hasLoad) {
            this.utilVue.loadHide()
            this.utilMessage.success('数据刷新完成')
          }
          if (response.data && response.data.length > 0) {
            this.workbenchListMenu = response.data
          }
          this.$refs.setMenuQuick.setUserMenuList(this.workbenchListMenu)
        }
      })
    },

    // 菜单激活
    menuActiveCall() {
      this.getCountInfoList()
      this.$refs.taskTodo.loadData()
    }
  },
  mounted() {
    //用户信息可能还未获取到，轮询(最多5次,每次500ms)
    let times = 0
    let interval = setInterval(() => {
      if (!this.user.code && times < 5) {
        this.user = this.utils.getCurrentUser()
        if (this.strings.isBlank(this.user.avatarUrl)) {
          // eslint-disable-next-line global-require
          this.user.avatarUrl = require('@/assets/icon/dept/hp.jpg')
        }
      } else {
        clearInterval(interval)
        this.initWorkbench()
        return
      }
      times++
    }, 500)

    setTimeout(() => {
      this.getMenuQuickList()
      this.getCountInfoList()
    }, 2000)
  },
}
</script>
<style lang="scss">
@import '../../styles/version1/home_dashboard.scss';
@import "../../styles/color.scss";
</style>
